package com.sgb.kjwl.view.ui.activity.packers;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;

import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;

import com.apeng.permissions.EsayPermissions;
import com.apeng.permissions.OnPermission;
import com.chuanglan.shanyan_sdk.OneKeyLoginManager;

import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.GsonManager;
import com.sgb.kjwl.aspectj.login.LoginCheck;
import com.sgb.kjwl.databinding.AtTeamOfferDetailBinding;
import com.sgb.kjwl.di.packers.DaggerPackersComponent;
import com.sgb.kjwl.di.packers.PackersModule;
import com.sgb.kjwl.model.entity.LoginEntity;
import com.sgb.kjwl.model.entity.UserMsgEntity;
import com.sgb.kjwl.model.entity.self.SelfTeamOfferEntity;
import com.sgb.kjwl.model.entity.user.OneKeyLoginEntity;
import com.sgb.kjwl.utils.ConfigUtils;
import com.sgb.kjwl.utils.NumberConstant;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LoginEvent;
import com.sgb.kjwl.view.ui.activity.pick.PickInquireByLetterActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.swgk.core.mmkvutil.CacheMarker;
import com.sgb.kjwl.viewmodel.packers.TeamOfferDetailModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.mmkvutil.MkvUtils;
import com.im.immodel.IMUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.tencent.smtt.sdk.WebSettings;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import javax.inject.Inject;

/**
 * @author liwei
 * @date 2021/1/13
 * description:工种报价详情
 */
public class TeamOfferDetailActivity extends AppActivity {

    private AtTeamOfferDetailBinding binding;

    @Inject
    TeamOfferDetailModel viewModel;

    private  boolean  isAttention = false;

    public static void start(Context context, String no) {
        Intent intent = new Intent();
        intent.setClass(context, TeamOfferDetailActivity.class);
        intent.putExtra("no", no);
        context.startActivity(intent);
    }

    @Override
    protected boolean statusBarDark() {
        return false;
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerPackersComponent.builder().appComponent(appComponent).packersModule(new PackersModule(this)).build().inject(this);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.at_team_offer_detail);
        binding.setViewModel(viewModel);
        binding.linAttention.setOnClickListener(this);
        binding.linIm.setOnClickListener(this);
        binding.linHanxun.setOnClickListener(this);
        binding.btnTeamContact.setOnClickListener(this);

        viewModel.detailOffer(getIntent().getStringExtra("no"));
    }

    @Override
    protected void init() {
        viewModel.getH5Url(getIntent().getStringExtra("no"));
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.lin_attention) {
            followCheck();
        } else if (id == R.id.lin_im) {
            if (TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                jumpLogin();
            } else {
                viewModel.detailOfferIm(getIntent().getStringExtra("no"));
            }
        } else if (id == R.id.lin_hanxun) {
            ask();
        } else if (id == R.id.btn_team_contact) {
            tell();
        }
    }

    public void getUrl(String url) {
        binding.progress.show();
        binding.progress.setColor(ContextCompat.getColor(this,R.color.translucent));
        binding.webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        binding.webView.getSettings().setDomStorageEnabled(true);
        binding.webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        binding.webView.getSettings().setAppCacheEnabled(true);
        binding.webView.loadUrl(url);
    }

    public void detailEmploymentIm(SelfTeamOfferEntity data) {
        if (!TextUtils.isEmpty(data.getImId())) {
            viewModel.findCustomerServiceImAccount(data.getImId());
        } else {
            MToast.showToast(this, "招标方未设置客服人员，不支持交流。");
        }
    }

    public void detailTeamTelephone(SelfTeamOfferEntity entity){
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + entity.getContactPhone());
        intent.setData(data);
        startActivity(intent);
    }

    public void onBackAccount(String msg) {
        IMUtils.getInstance().buildSingleTalking(msg);
    }

    public void jumpLogin() {
        boolean shanyan = MkvUtils.get().getBoolean(MkvUtils.CommomData, CacheMarker.ShanYan, false);
        if (shanyan) {
            //校验权限
            //申请动态权限
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                //6.0以上运行时权限处理
                EsayPermissions.with(TeamOfferDetailActivity.this).constantRequest().permission(PERMISSIONS).request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
                        openLoginPage();
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        openLoginPage();
                    }
                });

            } else {
                //有权限
                openLoginPage();
            }

        } else {
            VerificationCodeLoginActivity.start(TeamOfferDetailActivity.this, EventConstant.EVENT_TEAM_OFFER_DETAIL_JUMP);
        }
    }

    /**
     * 闪验
     */
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.READ_PHONE_STATE
    };

    /**
     * 拉起授权页
     */
    private void openLoginPage() {
        //设置授权页样式
        OneKeyLoginManager.getInstance().setAuthThemeConfig(ConfigUtils.getCJSConfig(this));
        //开始拉取授权页
        DialogHelper.showProgressDialog(this, null, "数据加载中", 0, true, null).setCanceledOnTouchOutside(true);
        OneKeyLoginManager.getInstance().openLoginAuth(false, (code, result) -> {
            DialogHelper.dismissProgressDialog();
            if (code != NumberConstant.NUMBER_ONE_THOUSAND) {
                VerificationCodeLoginActivity.start(TeamOfferDetailActivity.this, EventConstant.EVENT_TEAM_OFFER_DETAIL_JUMP);
            }
        }, (code, result) -> {
            DialogHelper.dismissProgressDialog();
            if (code == NumberConstant.NUMBER_ONE_THOUSAND) {
                OneKeyLoginEntity oneKeyLoginEntity = GsonManager.getInstance().getGson().fromJson(result, OneKeyLoginEntity.class);
                oneKeyLoginEntity.setPlateform("Android");
                viewModel.oneKeyLogin(oneKeyLoginEntity);
            }
        });
    }

    /**
     * 一键登录成功
     *
     * @param loginEntity
     * @param phoneNumber
     */
    public void loginSucceed(LoginEntity loginEntity, String phoneNumber) {
        LoginEvent loginEvent = new LoginEvent();
        loginEvent.setMessageData(phoneNumber);
        loginEvent.setMessageTag(EventConstant.EVENT_TEAM_OFFER_DETAIL_JUMP);
        loginEvent.setObject(loginEntity);
        EventBus.getDefault().postSticky(loginEvent);
    }

    public void getUserMsgSucceed(UserMsgEntity userMsgEntity) {
        LoginEvent loginEvent = new LoginEvent();
        loginEvent.setMessageTag(EventConstant.EVENT_USER_MSG);
        loginEvent.setMessageData(userMsgEntity);
        EventBus.getDefault().postSticky(loginEvent);
    }

    public void detailOffer(SelfTeamOfferEntity data) {
        String userNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, "");
        if (!TextUtils.isEmpty(userNo) && data != null && userNo.equals(data.getUserNo())) {
            binding.linDetailTool.setVisibility(View.GONE);
        } else {
            binding.linDetailTool.setVisibility(View.VISIBLE);
        }

        if (data != null){
            isAttention = data.isFocus();
            follow();
        }
    }

    public void follow() {
        if (!isAttention) {
            binding.ivAttention.setImageResource(R.mipmap.gz_orange_no_select);
            binding.tvAttention.setTextColor(ContextCompat.getColor(this, R.color.color_666666));
            binding.tvAttention.setText("关注");
            isAttention = true;
        } else {
            binding.ivAttention.setImageResource(R.mipmap.gz_orange);
            binding.tvAttention.setTextColor(ContextCompat.getColor(this, R.color.color_main));
            binding.tvAttention.setText("已关注");
            isAttention = false;
        }
    }

    @LoginCheck(needRealName = true)
    public void followCheck(){
        viewModel.follow(isAttention,getIntent().getStringExtra("no"));
    }

    @LoginCheck(needRealName = true)
    public void ask(){
        String no = getIntent().getStringExtra("no");
        PickInquireByLetterActivity.start(TeamOfferDetailActivity.this, no, "team", "", "", "4");
    }

    @LoginCheck
    public void tell(){
        viewModel.detailTeamTelephone(getIntent().getStringExtra("no"));
    }
}
